package com.qf.lja.servlet;


import com.qf.lja.dao.UserDao;
import com.qf.lja.enity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/UserEdit.do")
public class UserEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8"); // 设置请求参数的编码为UTF-8
        resp.setCharacterEncoding("UTF-8");

        String user_id = req.getParameter("user_id");
        System.out.println("获取到, user_id : " + user_id);

        if (user_id == null || user_id.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID不能为空");
            return; // 结束方法的执行
        }

        UserDao userDao = new UserDao();
        User user = userDao.findByUserId(Integer.parseInt(user_id));

        if (user == null) {
            resp.sendError(500, "查无此人");
        } else {
            System.out.println("查到此人了 name , " + user.getUserName());
            req.setAttribute("user", user);
            req.getRequestDispatcher("user_edit.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8"); // 设置请求参数的编码为UTF-8
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String state = req.getParameter("state");
        String userId = req.getParameter("user_id");
        System.out.println(username + " " + password + " " + role + " " + state);

        // 获取用户ID

        // 空值检查
        if (userId == null || userId.isEmpty()) {
            System.out.println("ID == null");
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID不能为空");
            return; // 结束方法的执行
        }
        // 更新用户信息
        UserDao userDao = new UserDao();
        boolean success = userDao.update(Integer.parseInt(userId), username, password, role, state);
        if (success) {
            resp.sendRedirect(req.getContextPath() + "/update_success.jsp");
        } else {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新用户信息失败");
        }
    }
}
